package com.zlm.service;

import com.zlm.entity.User;
import com.zlm.mapper.UserMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

/**
 * 自定义用户查询 & 密码自动升级的类
 */

@Service
public class MyUserDetailService implements UserDetailsService, UserDetailsPasswordService {

    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.loadUserByUsername(username);
        if (ObjectUtils.isEmpty(user)) {
            throw new RuntimeException("用户不存在!");
        }
        user.setRoles(userMapper.getRolesByUid(user.getId()));
        return user;
    }

    /**
     * 密码自动升级的方法
     * @param user
     * @param newPassword
     * @return
     */
    // 这个使用的是非常安全的
    // 现在默认的就是BCript然后他们的密码都会变为{bc}开头的了
    @Override
    public UserDetails updatePassword(UserDetails user, String newPassword) {
        Integer result = userMapper.updatePassword(user.getUsername(), newPassword);
        if (result == 1) {
            ((User) user).setPassword(newPassword);
        }
        return user;
    }
}
